package com.jiangyg.mall.core.support.web;

import com.jiangyg.mall.core.support.restful.Result;
import com.jiangyg.mall.core.utils.Logger;
import com.jiangyg.mall.core.utils.WebUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.server.ServerResponse;
import org.springframework.web.reactive.result.view.ViewResolver;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.function.Supplier;

/**
 * 类描述：Reactive 服务异常处理
 * <p>参考 SentinelGatewayBlockExceptionHandler 类开发的，</p>
 * <p>一般用于 gateway 异常处理，执行顺序应该遵守：</p>
 * <p> SentinelGatewayBlockExceptionHandler -> ReactiveWebExceptionHandler -> DefaultErrorWebExceptionHandler </p>
 * <p>DefaultErrorWebExceptionHandler 优先级一般为 -1 所以本类 Order 一般定义 -2 </p>
 *
 * @author jiangyg
 * @version 4.0
 * @date 2022-10-13
 */
@Slf4j
public class WebFluxExceptionHandler implements WebExceptionHandler {

    private List<ViewResolver> viewResolvers;

    private List<HttpMessageWriter<?>> messageWriters;

    public WebFluxExceptionHandler(List<ViewResolver> viewResolvers, ServerCodecConfigurer serverCodecConfigurer) {
        this.viewResolvers = viewResolvers;
        this.messageWriters = serverCodecConfigurer.getWriters();
    }

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
        if (exchange.getResponse().isCommitted()) {
            return Mono.error(ex);
        }
        Logger.info(log, () -> String.format("请求[%s]出现异常", WebUtils.getRequestPath(exchange)), ex);
        return ServerResponse
                .status(HttpStatus.OK)
                .contentType(MediaType.APPLICATION_JSON)
                .bodyValue(Result.error().toJSONString())
                .flatMap(response -> writeResponse(response, exchange));
    }

    private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
        return response.writeTo(exchange, contextSupplier.get());
    }

    private final Supplier<ServerResponse.Context> contextSupplier = () -> new ServerResponse.Context() {

        @Override
        public List<HttpMessageWriter<?>> messageWriters() {
            return WebFluxExceptionHandler.this.messageWriters;
        }

        @Override
        public List<ViewResolver> viewResolvers() {
            return WebFluxExceptionHandler.this.viewResolvers;
        }

    };

}
